package com.jwgf.smarowindingmachine_unity.ui;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.util.SparseIntArray;
import android.widget.Button;
import android.widget.ImageButton;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.jwgf.common.AppContext;
import com.jwgf.common.FragmentFactory;
import com.jwgf.common.FragmentRelationShip;
import com.jwgf.smarowindingmachine_unity.R;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class SwitchPageManager {
    private static SwitchPageManager switchPageManager;

    private static final String SHORTCUT_ONE = "shortcut_one";
    private static final String SHORTCUT_TWO = "shortcut_two";
    private static final String SHORTCUT_THREE = "shortcut_three";

    private SharedPreferences sp = AppContext.getInstance().getSharedPreferences("ShortCutSetting",
            Context.MODE_PRIVATE);

    // 当前显示页面的id
    private int firstID = R.id.machine_state_button;
    private int secondID = R.id.running_state_button;
    //缓存的页面id
    private SparseIntArray map = new SparseIntArray(4);

    private SwitchPageManager() {
        map.put(R.id.machine_state_button, R.id.running_state_button);
        map.put(R.id.parameter_setting_button, R.id.btn_system);
        map.put(R.id.product_manage_button, R.id.pm_productionset);
        map.put(R.id.equipment_maintenance_button, R.id.btn_function);
    }

    public static SwitchPageManager getInstance() {
        if (switchPageManager == null) {
            switchPageManager = new SwitchPageManager();
        }
        return switchPageManager;
    }

    public void init(FragmentManager fm) {
        if (fm.getFragments().isEmpty()) {
            String titleTag = FragmentRelationShip.getInstance().getTitleTag();
            String mainTag = FragmentRelationShip.getInstance().getMainTag();
            String subTag = FragmentRelationShip.getInstance().getTag(R.id.machine_state_button);
            String contentTag = FragmentRelationShip.getInstance().getTag(map.get(R.id.machine_state_button));
            String loginTag = FragmentRelationShip.getInstance().getLoginTag();
            FragmentTransaction ft = fm.beginTransaction();
            Fragment titleFragment = FragmentFactory.createInstance(titleTag);
            Fragment mainMenuFragment = FragmentFactory.createInstance(mainTag);
            Fragment subMenuFragment = FragmentFactory.createInstance(subTag);
            Fragment contentFragment = FragmentFactory.createInstance(contentTag);
            Fragment loginFragment = FragmentFactory.createInstance(loginTag);
            ft.add(R.id.title_layout, titleFragment, titleTag);
            ft.add(R.id.main_menu_layout, mainMenuFragment, mainTag);
            ft.add(R.id.second_menu_layout, subMenuFragment, subTag);
            ft.add(R.id.content_layout, contentFragment, contentTag);
            ft.add(R.id.content_layout, loginFragment, loginTag).hide(loginFragment);
            ft.commitNow();
            printTag();
        }
    }

    private void printTag() {
        String tag = SwitchPageManager.class.getCanonicalName();
        String secondMenuTag = FragmentRelationShip.getInstance().getTag(firstID);
        String contentTag = FragmentRelationShip.getInstance().getTag(secondID);
        Log.i(tag.substring(tag.lastIndexOf('.') + 1),
                secondMenuTag.substring(secondMenuTag.lastIndexOf('.') + 1)
                        + "-" + contentTag.substring(contentTag.lastIndexOf('.') + 1));
    }

    public void switchMainMenu(FragmentManager fm, int firstID) {
        switchShortcut(fm, firstID, map.get(firstID));
    }

    public void switchSecondMenu(FragmentManager fm, int secondID) {
        switchShortcut(fm, firstID, secondID);
    }

    public void switchShortcut(FragmentManager fm, int firstID, int secondID) {
        if (this.firstID != firstID) {
            FragmentTransaction ft = fm.beginTransaction();
            // Hide second menu fragment
            String menuTag = FragmentRelationShip.getInstance().getTag(this.firstID);
            MenuFragment menu = (MenuFragment) fm.findFragmentByTag(menuTag);
            ft.hide(menu);
            // Show target menu fragment
            String menuTagTarget = FragmentRelationShip.getInstance().getTag(firstID);
            MenuFragment menuTarget = (MenuFragment) fm.findFragmentByTag(menuTagTarget);
            if (menuTarget != null) {
                ft.show(menuTarget);
            } else {
                menuTarget = (MenuFragment) FragmentFactory.createInstance(menuTagTarget);
                ft.add(R.id.second_menu_layout, menuTarget, menuTagTarget);
            }
            // Hide content fragment
            String contentTag = FragmentRelationShip.getInstance().getTag(this.secondID);
            Fragment content = fm.findFragmentByTag(contentTag);
            if (content != null) {
                ft.hide(content);
            }
            // Show target login and content fragment
            if (FragmentRelationShip.getInstance().getWriteLevel(secondID) == 0) {
                LoginFragment login = (LoginFragment) fm.findFragmentByTag(FragmentRelationShip.getInstance().getLoginTag());
                ft.hide(login);
                String contentTagTarget = FragmentRelationShip.getInstance().getTag(secondID);
                Fragment contentTarget = fm.findFragmentByTag(contentTagTarget);
                if (contentTarget != null) {
                    ft.show(contentTarget);
                } else {
                    contentTarget = FragmentFactory.createInstance(contentTagTarget);
                    ft.add(R.id.content_layout, contentTarget, contentTagTarget);
                }
            } else {
                int writeLevel = FragmentRelationShip.getInstance().getWriteLevel(secondID);
                LoginFragment login = (LoginFragment) fm.findFragmentByTag(FragmentRelationShip.getInstance().getLoginTag());
                if (LoginFragment.getWriteLevel() >= writeLevel) {
                    ft.hide(login);
                    String contentTagTarget = FragmentRelationShip.getInstance().getTag(secondID);
                    Fragment contentTarget = fm.findFragmentByTag(contentTagTarget);
                    if (contentTarget != null) {
                        ft.show(contentTarget);
                    } else {
                        contentTarget = FragmentFactory.createInstance(contentTagTarget);
                        ft.add(R.id.content_layout, contentTarget, contentTagTarget);
                    }
                } else {
                    ft.show(login);
                    login.registerRunnable(new Runnable() {

                        @Override
                        public void run() {
                            login(fm);
                        }
                    });
                }
            }
            ft.commitNow();
            // Switch first menu button
            getFirstMenu(fm).switchSelection(firstID);
            this.firstID = firstID;
            // Switch second menu button
            getSecondMenu(fm, firstID).switchSelection(secondID);
            map.put(firstID, secondID);
            this.secondID = secondID;
        } else {
            if (this.secondID != secondID) {
                FragmentTransaction ft = fm.beginTransaction();
                // Hide content fragment
                String contentTag = FragmentRelationShip.getInstance().getTag(this.secondID);
                Fragment content = fm.findFragmentByTag(contentTag);
                if (content != null) {
                    ft.hide(content);
                }
                // Show target login and content fragment
                if (FragmentRelationShip.getInstance().getWriteLevel(secondID) == 0) {
                    LoginFragment login = (LoginFragment) fm.findFragmentByTag(FragmentRelationShip.getInstance().getLoginTag());
                    ft.hide(login);
                    String contentTagTarget = FragmentRelationShip.getInstance().getTag(secondID);
                    Fragment contentTarget = fm.findFragmentByTag(contentTagTarget);
                    if (contentTarget != null) {
                        ft.show(contentTarget);
                    } else {
                        contentTarget = FragmentFactory.createInstance(contentTagTarget);
                        ft.add(R.id.content_layout, contentTarget, contentTagTarget);
                    }
                } else {
                    int writeLevel = FragmentRelationShip.getInstance().getWriteLevel(secondID);
                    LoginFragment login = (LoginFragment) fm.findFragmentByTag(FragmentRelationShip.getInstance().getLoginTag());
                    if (LoginFragment.getWriteLevel() >= writeLevel) {
                        ft.hide(login);
                        String contentTagTarget = FragmentRelationShip.getInstance().getTag(secondID);
                        Fragment contentTarget = fm.findFragmentByTag(contentTagTarget);
                        if (contentTarget != null) {
                            ft.show(contentTarget);
                        } else {
                            contentTarget = FragmentFactory.createInstance(contentTagTarget);
                            ft.add(R.id.content_layout, contentTarget, contentTagTarget);
                        }
                    } else {
                        ft.show(login);
                        login.registerRunnable(new Runnable() {

                            @Override
                            public void run() {
                                login(fm);
                            }
                        });
                    }
                }
                ft.commitNow();
                // Switch second menu button
                getSecondMenu(fm, firstID).switchSelection(secondID);
                map.put(firstID, secondID);
                this.secondID = secondID;
            }
        }
        printTag();

    }

    private void login(FragmentManager fm) {
        FragmentTransaction ft = fm.beginTransaction();
        LoginFragment login = (LoginFragment) fm.findFragmentByTag(FragmentRelationShip.getInstance().getLoginTag());
        ft.hide(login);
        String contentTagTarget = FragmentRelationShip.getInstance().getTag(map.get(firstID));
        Fragment contentTarget = fm.findFragmentByTag(contentTagTarget);
        if (contentTarget != null) {
            ft.show(contentTarget);
        } else {
            contentTarget = FragmentFactory.createInstance(contentTagTarget);
            ft.add(R.id.content_layout, contentTarget, contentTagTarget);
        }
        ft.commit();
    }


    public void switch2Page(FragmentManager fm, String firstTag, String secondTag) {
        int firstID = FragmentRelationShip.getInstance().getId(firstTag);
        int secondID = FragmentRelationShip.getInstance().getId(secondTag);
        switchShortcut(fm, firstID, secondID);
    }

    public MenuFragment getFirstMenu(FragmentManager fm) {
        String tag = FragmentRelationShip.getInstance().getMainTag();
        return ((MenuFragment) fm.findFragmentByTag(tag));
    }

    public MenuFragment getSecondMenu(FragmentManager fm, int firstID) {
        String tag = FragmentRelationShip.getInstance().getTag(firstID);
        return ((MenuFragment) fm.findFragmentByTag(tag));
    }

    public void shortCut1Action(FragmentManager fm) {
        String shortcut1 = sp.getString(SHORTCUT_ONE, "");
        String[] array;
        if (shortcut1.contains("-")) {
            array = shortcut1.split("-");
            switch2Page(fm, array[0], array[1]);
        }
    }

    public void shortCut2Action(FragmentManager fm) {
        String shortcut1 = sp.getString(SHORTCUT_TWO, "");
        String[] array;
        if (shortcut1.contains("-")) {
            array = shortcut1.split("-");
            switch2Page(fm, array[0], array[1]);
        }
    }

    public void shortCut3Action(FragmentManager fm) {
        String shortcut1 = sp.getString(SHORTCUT_THREE, "");
        String[] array;
        if (shortcut1.contains("-")) {
            array = shortcut1.split("-");
            switch2Page(fm, array[0], array[1]);
        }
    }

    public void setShortCut1(Activity activity) {
        String tag = FragmentRelationShip.getInstance().getTag(firstID) + "-"
                + FragmentRelationShip.getInstance().getTag(secondID);
        sp.edit().putString(SHORTCUT_ONE, tag).commit();
        saveShortCutIcon(SHORTCUT_ONE, activity);
    }

    public void setShortCut2(Activity activity) {
        String tag = FragmentRelationShip.getInstance().getTag(firstID) + "-"
                + FragmentRelationShip.getInstance().getTag(secondID);
        sp.edit().putString(SHORTCUT_TWO, tag).commit();
        saveShortCutIcon(SHORTCUT_TWO, activity);
    }

    public void setShortCut3(Activity activity) {
        String tag = FragmentRelationShip.getInstance().getTag(firstID) + "-"
                + FragmentRelationShip.getInstance().getTag(secondID);
        sp.edit().putString(SHORTCUT_THREE, tag).commit();
        saveShortCutIcon(SHORTCUT_THREE, activity);
    }

    public Drawable loadShortCutIcon1() {
        return loadShortCutIcon(SHORTCUT_ONE);
    }

    public Drawable loadShortCutIcon2() {
        return loadShortCutIcon(SHORTCUT_TWO);
    }

    public Drawable loadShortCutIcon3() {
        return loadShortCutIcon(SHORTCUT_THREE);
    }

    private Drawable loadShortCutIcon(String shortCut) {
        String tags = sp.getString(shortCut, "");
        String[] tag = null;
        if (tags.contains("-")) {
            tag = tags.split("-");
        } else {
            sp.edit().remove(shortCut).commit();
            return null;
        }
        int firstID = FragmentRelationShip.getInstance().getId(tag[0]);
        int secondID = FragmentRelationShip.getInstance().getId(tag[1]);
        if (firstID > 0 && secondID > 0) {
            File fileDir = AppContext.getInstance().getFilesDir();
            String fileName = shortCut + ".png";
            File file = new File(fileDir, fileName);
            if (file.exists()) {
                Bitmap bm = BitmapFactory.decodeFile(file.getAbsolutePath());
                Drawable d = new BitmapDrawable(AppContext.getInstance().getResources(), bm);
                return d;
            } else {
                sp.edit().remove(shortCut).commit();
                return null;
            }
        } else {
            sp.edit().remove(shortCut).commit();
            return null;
        }
    }

    private void saveShortCutIcon(String shortCut, Activity activity) {
        Bitmap bitmap = getButtonBitmap(activity);

        File fileDir = AppContext.getInstance().getFilesDir();
        String fileName = shortCut + ".png";
        File file = new File(fileDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bitmap.compress(CompressFormat.PNG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private Bitmap getButtonBitmap(Activity activity) {
        Button button = activity.findViewById(secondID);
        Drawable[] d = button.getCompoundDrawables();
        Bitmap bitmap = ((BitmapDrawable) d[1]).getBitmap();
        return bitmap;
    }
}
